package com.umeox.watch.moto.apiclient.http.client;


import com.umeox.watch.httpclient.core.constant.HttpMethod;
import com.umeox.watch.httpclient.core.constant.Scheme;
import com.umeox.watch.moto.apiclient.http.adapter.HttpClientAdapter;
import com.umeox.watch.moto.apiclient.http.adapter.HttpClientAdapterImpl;
import com.umeox.watch.moto.apiclient.http.callback.WaasCallback;
import com.umeox.watch.moto.apiclient.http.request.WaasRequest;
import com.umeox.watch.moto.apiclient.http.response.WaasResponse;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Interceptor;

public class APIClientImpl implements APIClient {
    private boolean initialized = false;
    private HttpClientAdapter clientAdapter;

    APIClientImpl() {
    }

    public void init(InitializeConfig config) {
        if (this.initialized) {
            throw new RuntimeException("can not duplicated initialize !");
        } else {
            HttpClientAdapter adapter = config.adapter;
            if (adapter == null) {
                adapter = new HttpClientAdapterImpl(config);
            }
            this.clientAdapter = adapter;
            this.initialized = true;
        }
    }

    @Override
    public WaasResponse send(WaasRequest request) {
        checkInitialize();
        checkNull(request);
        return clientAdapter.send(request);
    }

    @Override
    public void send(WaasRequest request, WaasCallback callback) {
        checkInitialize();
        checkNull(request, callback);
        clientAdapter.send(request, callback);
    }

    private void checkInitialize() {
        if (!APIClientImpl.this.initialized) {
            throw new RuntimeException("initialize first");
        }
    }

    private void checkNull(WaasRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("request can not be null");
        } else if (HttpMethod.GET != request.getMethod()
                && HttpMethod.POST_JSON != request.getMethod()
                && HttpMethod.POST_FILE != request.getMethod()) {
            throw new IllegalArgumentException("only support POST&GET at present");
        }
    }

    private void checkNull(WaasRequest request, WaasCallback callback) {
        checkNull(request);
        if (callback == null) {
            throw new IllegalArgumentException("callback can not be null");
        }
    }

    public static class InitializeConfig {
        public Scheme scheme;
        public String host;
        public String appKey;
        public String appSecret;
        public String accessToken;
        public HttpClientAdapter adapter;
        public List<Interceptor> interceptors;

        public InitializeConfig() {
        }

        public void addInterceptor(Interceptor interceptor) {
            if (interceptors == null) {
                interceptors = new ArrayList<>();
            }
            interceptors.add(interceptor);
        }
    }
}
